package com.google.android.daca;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.daca.service.DoodleRESTService;
import com.google.android.daca.types.Poll;

/**
 * Login screen to choose a new name to be used for polls or edit an existing previously saved one 
 * and optionally a Doodle poll ID (if the user started the DACA app himself and not through a URL). 
 * Then forward to the next activity.
 * 
 * @author epetkov
 */
public class LoginActivity extends Activity 
{
	// prefs
	public static final String DOODLE_PRIVATE_PREFS = "DOODLE_PRIVATE_PREFS";
	public static final String DOODLE_NAME = "DOODLE_NAME";
	
	private static final String CLASS_TAG = LoginActivity.class.getSimpleName();
	
	private SharedPreferences doodlePrefs;
	private String savedDoodleName;
	
    private Button goToPollButton;
    private EditText doodleName; 
    private EditText doodlePollID;
    
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
        Log.v(DACAConstants.APP_LOG_TAG, " " + LoginActivity.CLASS_TAG + " onCreate");

        setContentView(R.layout.login);

        // if the user has some saved doodle name in a previous run, show it
        doodleName = (EditText) findViewById(R.id.doodle_name);
        doodlePrefs = getSharedPreferences(LoginActivity.DOODLE_PRIVATE_PREFS, Context.MODE_PRIVATE);
        savedDoodleName = doodlePrefs.getString(LoginActivity.DOODLE_NAME, "N/A");
        doodleName.setText(savedDoodleName);
        
        // if the app is started via a doodle url click, preselect the Doodle ID
        doodlePollID = (EditText) findViewById(R.id.doodle_poll_id);
        String pollID = getIntent().getStringExtra(getResources().getString(R.string.extra_poll_id));
        if (pollID != null)
        {
        	doodlePollID.setText(pollID);
        }
        
        goToPollButton = (Button) findViewById(R.id.go_to_poll_button);
        goToPollButton.setOnClickListener(new OnClickListener() 
        	{
				@Override
				public void onClick(View v) 
				{
					 goToPoll();
				}
        	}
        );
    }   
	
    @Override
    protected void onResume() {
        super.onResume();
        Log.v(DACAConstants.APP_LOG_TAG, " " + LoginActivity.CLASS_TAG + " onResume");
    }
    
    /**
     * Validate supplied data and then go to poll 
     * with given poll ID and participant name.
     */
    private void goToPoll() 
    {
        if (!validateUIFields())
            return;

        Intent intent = new Intent(DACAConstants.INTENT_ACTION_VIEW_POLL);
        
        String possiblyChangedDoodleName = doodleName.getText().toString();
        if (!possiblyChangedDoodleName.equals(savedDoodleName))
        {
        	// user has updated his doodle name, so save the new one as a preference
        	Editor doodlePrefsEditor = doodlePrefs.edit();
        	doodlePrefsEditor.putString(LoginActivity.DOODLE_NAME, possiblyChangedDoodleName);
        	doodlePrefsEditor.commit();
        	intent.putExtra(getResources().getString(R.string.extra_doodle_name), possiblyChangedDoodleName);
        }
        else 
        {
        	// user has used the same doodle name as the previously saved, so use it
        	intent.putExtra(getResources().getString(R.string.extra_doodle_name), savedDoodleName);
        }
        
        Poll poll = null;
        
        String pollID = doodlePollID.getText().toString();
        DoodleRESTService doodleRestService = new DoodleRESTService();
        try
        {
        	poll = doodleRestService.getPollByID(pollID);
        }
        catch (Exception e) 
        {
			Log.e(DACAConstants.APP_LOG_TAG, e.getMessage());
	        new AlertDialog.Builder(this).setTitle(
	               	getResources().getString(R.string.alert_label)).setMessage(
	               			getResources().getString(R.string.doodle_poll_id_not_valid)).setPositiveButton("Continue",
	               							                         new android.content.DialogInterface.OnClickListener() 
	   												                 {				
	   												                     public void onClick(DialogInterface dialog, int arg1) 
	   												                     {
	   												                         // in this case, don't need to do anything other than close alert
	   												                     }
	   												                 }).show();
	        return;
		}
        
        
        // put the Poll object and the poll ID in the intent
        poll.setPollID(pollID);
        intent.putExtra(getResources().getString(R.string.extra_poll_object), poll);
        
        // call next Activity VIEW_POLL
        startActivity(intent);
    }
    
    /**
     * Validate form fields.
     * 
     */
    private boolean validateUIFields()
    {
        boolean valid = true;
        
        StringBuilder validationText = new StringBuilder();
        if (doodleName.getText() == null || doodleName.getText().toString().trim().length() == 0)
        {
            validationText.append(getResources().getString(R.string.doodle_name_not_supplied_message));
            valid = false;
        }
        if (doodlePollID.getText() == null || doodlePollID.getText().toString().trim().length() == 0)
        {
        	if (!valid)
        	{
        		validationText.append("\n");
        	}
        	validationText.append(getResources().getString(R.string.doodle_poll_id_not_supplied_message));
        	valid = false;
        }
        if (!valid) 
        {
            new AlertDialog.Builder(this).setTitle(
            	getResources().getString(R.string.alert_label)).setMessage(
            		validationText.toString()).setPositiveButton("Continue",
            							                         new android.content.DialogInterface.OnClickListener() 
												                 {				
												                     public void onClick(DialogInterface dialog, int arg1) 
												                     {
												                         // in this case, don't need to do anything other than close alert
												                     }
												                 }).show();
        }
        
        return valid;
    }
}
